package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@RequestMapping("/admin/product")
public class UploadFileController {

    @Value("${img.url}")
    private String imgUrl;

    // 上传图片
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception {

        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        byte[] bytes = file.getBytes();
        // 1、引入坐标
        String path = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        ClientGlobal.init(path);
        // 2、上传文件请求，找跟踪器
        TrackerClient client = new TrackerClient();
        TrackerServer trackerServer = client.getConnection();
        // 3、连接存储节点
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
        // 4、上传图片
        String filePath = storageClient1.upload_file1(bytes, extension, null);
        return Result.ok(imgUrl + filePath);
    }
}